<template>
  <div class="app-container">
    <el-row>

      <!-- 优化页面 -->
      <el-col>
        <el-row :gutter="10" class="mb8">
        </el-row>
      <el-row>
        <el-col :span="10"></el-col>
          <el-col :span="8">
              <el-progress type="dashboard" :percentage="percentage" :width="200" :stroke-width="15" :color="colors">
                <template #default="{ percentage }">
                  <span class="percentage-value">{{ percentage.toFixed(0) }}%</span>
                  <span class="percentage-label">优化进度</span>
                </template>
              </el-progress>
       
          </el-col>
      </el-row>
        <el-row>
          <div
            style="font-size: 16px; font-weight: bold; color: var(--el-color-primary); padding: 15px 0; margin: 10px 0; border-bottom: 2px solid var(--el-color-primary); display: flex; align-items: center;">
            <i class="el-icon-document" style="margin-right: 8px;"></i>
            优化中队列
          </div>
        </el-row>
        <el-row>
        <el-table v-loading="loading" :data="queueList" @selection-change="handleSelectionChange"
          :row-class-name="queueRowClassName">
          <el-table-column label="优化包名称" align="center" prop="name" />
          <el-table-column label="优化开始时间" align="center" prop="optimizeBeginTime">
            <template #default="scope">
              <span>{{ scope.row.optimizeBeginTime ? parseTime(scope.row.optimizeBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') :
                '——' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="原片总面积(m²)" align="center" prop="totalArea">
            <template #default="scope">
              <span>{{ scope.row.totalArea || '——' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="原片数" align="center" prop="plateNum">
            <template #default="scope">
              <span>{{ scope.row.plateNum || '——' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button v-if="scope.row.status != 2" link type="primary" icon="Delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="queueTotal > 0" :total="queueTotal" v-model:page="queueQueryParams.pageNum"
          v-model:limit="queueQueryParams.pageSize" @pagination="getQueueList" />
        </el-row>
        <el-row>
          <div
            style="font-size: 16px; font-weight: bold; color: var(--el-color-primary); padding: 15px 0; margin: 10px 0; border-bottom: 2px solid var(--el-color-primary); display: flex; align-items: center;">
            <i class="el-icon-document" style="margin-right: 8px;"></i>
            预优化列表
          </div>
        </el-row>
        <el-table v-loading="preLoading" :data="prePackageList" @selection-change="handleSelectionChange">
          <el-table-column label="优化包名称" align="center" prop="name" />
          <el-table-column label="优化开始时间" align="center" prop="optimizeBeginTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.optimizeBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="优化完成时间" align="center" prop="optimizeResult.createdTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.optimizeResult.createdTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="切裁率" align="center" prop="optimizeResult.rateOpt">
            <template #default="scope">
              <span>{{ formatWithPercent(scope.row.optimizeResult.rateOpt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="净切裁率" align="center" prop="optimizeResult.rateNoEdge">
            <template #default="scope">
              <span>{{ formatWithPercent(scope.row.optimizeResult.rateNoEdge) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成品总面积(m²)" align="center" prop="optimizeResult.glassArea">
            <template #default="scope">
              <span>{{ scope.row.optimizeResult.glassArea == null ? '——' : scope.row.optimizeResult.glassArea.toFixed(2)
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成品数" align="center" prop="optimizeResult.glassNumber" />
          <el-table-column label="原片总面积(m²)" align="center" prop="optimizeResult.totalArea">
            <template #default="scope">
              <span>{{ scope.row.optimizeResult.totalArea == null ? '——' : scope.row.optimizeResult.totalArea.toFixed(2)
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="原片数" align="center" prop="optimizeResult.originalNumber" />
          <el-table-column label="尾片宽度(mm)" align="center" prop="optimizeResult.residueLength" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260px">
            <template #default="scope">
              <div style="display: flex; justify-content: space-between; white-space: nowrap;">
                
                <el-button v-if="scope.row.optimizeResult.glassArea > 0" link type="primary"
                  @click="handleView(scope.row)">查看排版</el-button>
                <el-button v-else link type="primary"
                  @click="handleViewReason(scope.row)">查看原因</el-button>
                <el-button link type="primary" v-if="scope.row.optimizeResult.glassArea > 0"
                 @click="handleExportAll(scope.row)">导出生产文件</el-button>
                <el-dropdown>
                  <el-button link type="primary">
                    更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleReoptimize(scope.row,1)">重新优化</el-dropdown-item>
                      <el-dropdown-item  
                        @click="handleExportPackage(scope.row)">导出优化包</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.optimizeResult.glassArea > 0"
                        @click="handleTransform(scope.row)">正式优化</el-dropdown-item>
                      <el-dropdown-item @click="confirmDelete(scope.row)">删除</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.optimizeResult.glassArea > 0"
                         @click="handleTailPiece(scope.row)">查看余料</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.optimizeResult.glassArea > 0"
                          @click="handleTailPieceOptimize(scope.row)">尾片优化</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="preTotal > 0" :total="preTotal" v-model:page="preQueryParams.pageNum"
          v-model:limit="preQueryParams.pageSize" @pagination="getPreList" />


          <el-row>
          <div
            style="font-size: 16px; font-weight: bold; color: var(--el-color-primary); padding: 15px 0; margin: 10px 0; border-bottom: 2px solid var(--el-color-primary); display: flex; align-items: center;">
            <i class="el-icon-document" style="margin-right: 8px;"></i>
            正式优化列表
          </div>
        </el-row>
        <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
          <el-table-column label="优化包名称" align="center" prop="name" />
          <el-table-column label="优化开始时间" align="center" prop="optimizeBeginTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.optimizeBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="优化完成时间" align="center" prop="optimizeResult.createdTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.optimizeResult.createdTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="切裁率" align="center" prop="optimizeResult.rateOpt">
            <template #default="scope">
              <span>{{ formatWithPercent(scope.row.optimizeResult.rateOpt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="净切裁率" align="center" prop="optimizeResult.rateNoEdge">
            <template #default="scope">
              <span>{{ formatWithPercent(scope.row.optimizeResult.rateNoEdge) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成品总面积(m²)" align="center" prop="optimizeResult.glassArea">
            <template #default="scope">
              <span>{{ scope.row.optimizeResult.glassArea == null ? '——' : scope.row.optimizeResult.glassArea.toFixed(2)
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成品数" align="center" prop="optimizeResult.glassNumber" />
          <el-table-column label="原片总面积(m²)" align="center" prop="optimizeResult.totalArea">
            <template #default="scope">
              <span>{{ scope.row.optimizeResult.totalArea == null ? '——' : scope.row.optimizeResult.totalArea.toFixed(2)
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="原片数" align="center" prop="optimizeResult.originalNumber" />
          <el-table-column label="尾片宽度(mm)" align="center" prop="optimizeResult.residueLength" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260px">
            <template #default="scope">
              <div style="display: flex; justify-content: space-between; white-space: nowrap;">
                <el-button v-if="scope.row.optimizeResult.glassArea > 0" link type="primary"
                  @click="handleView(scope.row)">查看排版</el-button>
                <el-button v-else link type="primary"
                  @click="handleViewReason(scope.row)">查看原因</el-button>
                <el-button v-if="scope.row.optimizeResult.glassArea > 0" link type="primary" 
                   @click="handleExportAll(scope.row)">导出生产文件</el-button>
                   <el-dropdown>
                  

                  <el-button link type="primary">
                    更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu >
                      <el-dropdown-item   @click="handleReoptimize(scope.row,2)">重新优化</el-dropdown-item>
                      <el-dropdown-item 
                        @click="handleExportPackage(scope.row)">导出优化包</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.optimizeResult.glassArea > 0"
                        @click="handleConfirm(scope.row)">确认下发</el-dropdown-item>
                      <el-dropdown-item type="danger" @click="confirmDelete(scope.row)">删除</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.optimizeResult.glassArea > 0" 
                        @click="handleTailPiece(scope.row)">查看余料</el-dropdown-item>
                        <el-dropdown-item v-if="scope.row.optimizeResult.glassArea > 0"
                          @click="handleTailPieceOptimize(scope.row)">尾片优化</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改优化包进程管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="packageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="需求数量" prop="glassTypeNum">
          <el-input v-model="form.glassTypeNum" placeholder="请输入需求数量" />
        </el-form-item>
        <el-form-item label="优化包名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优化包名称" />
        </el-form-item>
        <el-form-item label="来源" prop="sources">
          <el-input v-model="form.sources" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item label="玻璃磨边量" prop="grind">
          <el-input v-model="form.grind" placeholder="请输入玻璃磨边量" />
        </el-form-item>
        <el-form-item label="是否为离线优化，为 1 算法会按箱架优化，0表示无序优化" prop="isOffline">
          <el-input v-model="form.isOffline" placeholder="请输入是否为离线优化，为 1 算法会按箱架优化，0表示无序优化" />
        </el-form-item>
        <el-form-item label="最大刀距离X" prop="max1Cut">
          <el-input v-model="form.max1Cut" placeholder="请输入最大刀距离X" />
        </el-form-item>
        <el-form-item label="最大货架数" prop="maxShelf">
          <el-input v-model="form.maxShelf" placeholder="请输入最大货架数" />
        </el-form-item>
        <el-form-item label="最小刀距-XZ" prop="min13Cut">
          <el-input v-model="form.min13Cut" placeholder="请输入最小刀距-XZ" />
        </el-form-item>
        <el-form-item label="最小刀距-X" prop="min1Cut">
          <el-input v-model="form.min1Cut" placeholder="请输入最小刀距-X" />
        </el-form-item>
        <el-form-item label="最小刀距-Y" prop="min2Cut">
          <el-input v-model="form.min2Cut" placeholder="请输入最小刀距-Y" />
        </el-form-item>
        <el-form-item label="掰边距" prop="minWaste">
          <el-input v-model="form.minWaste" placeholder="请输入掰边距" />
        </el-form-item>
        <el-form-item label="原片种类" prop="plateTypeNum">
          <el-input v-model="form.plateTypeNum" placeholder="请输入原片种类" />
        </el-form-item>
        <el-form-item label="原片底修边量" prop="trimBottom">
          <el-input v-model="form.trimBottom" placeholder="请输入原片底修边量" />
        </el-form-item>
        <el-form-item label="原片左修边量" prop="trimLeft">
          <el-input v-model="form.trimLeft" placeholder="请输入原片左修边量" />
        </el-form-item>
        <el-form-item label="原片右修边量" prop="trimRight">
          <el-input v-model="form.trimRight" placeholder="请输入原片右修边量" />
        </el-form-item>
        <el-form-item label="原片顶修边量" prop="trimTop">
          <el-input v-model="form.trimTop" placeholder="请输入原片顶修边量" />
        </el-form-item>
        <el-form-item label="厚度" prop="thickNess">
          <el-input v-model="form.thickNess" placeholder="请输入厚度" />
        </el-form-item>
        <el-form-item label="订单数" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入订单数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

     <el-dialog :title="title" v-model="openPdf" width="60%" append-to-body>
      <div class="controls" v-if="totalPages > 0">
        <el-button 
          type="primary"
          @click="currentPage--" 
          :disabled="currentPage <= 1"
          class="page-btn prev-btn"
        >
          上一页
        </el-button>
        <el-input 
          v-model="currentPage" 
          type="number" 
          :min="1" 
          :max="totalPages"
          style="width: 60px; text-align: center; margin: 0 10px;"
          @change="handlePageChange(currentPage)"
        />
        <span class="page-info">/ {{ totalPages }}</span>
        <el-button
          type="primary" 
          @click="currentPage++"
          :disabled="currentPage >= totalPages"
          class="page-btn next-btn"
        >
          下一页
        </el-button>
      </div>
      <PDF v-if="openPdf" :src="pdfSrc" 
      :page="currentPage"
      :pdfWidth="`${scale}%`"
      style="width: 100%; height: 80vh;" 
      @onComplete="pdfLoaded" 
      @onPageChange="handlePageChange" 
      
      ref="pdfViewer"
      >
      <template #pageTooltip="{ pageNumber, totalPages }">
        <div ref="tooltipRef">{{ updateTotalPages(totalPages) }}</div>
    </template>
    </PDF>
    </el-dialog> 



    <el-dialog title="查看余料" v-model="openSurplusMaterial" width="60%" append-to-body @closed="tailPieceList = []">
      <el-table :data="tailPieceList" border>
        <el-table-column label="所在原片id" prop="sn" />
        <el-table-column label="序号" prop="surplusNo" />
        <el-table-column label="余料宽度" prop="width" />
        <el-table-column label="余料高度" prop="height" />
      </el-table>
    </el-dialog>
    
    <el-dialog title="尾片优化" v-model="openTailPiece" width="60%" append-to-body :close-on-click-modal="false" :before-close="handleTailPieceOptimizeClose">
      <div class="tail-piece-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">尾片宽度：</span>
              <span class="info-value">{{ tailPieceWidth }} 毫米</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">尾片高度：</span>
              <span class="info-value">{{ tailPieceHeight }} 毫米</span>
            </div>
          </el-col>
        </el-row>
        <el-table v-if="tailPieceAddList.length > 0" :data="tailPieceAddList" border>
          <el-table-column label="宽度" prop="width" />
          <el-table-column label="长度" prop="length" />
          <el-table-column label="数量" prop="piecesNumber" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" @click="handleTailPieceOptimizeDelete(scope.row)" icon="Delete">删除</el-button>
            </template>
          </el-table-column>
       </el-table>
      </div>
      <div class="tail-piece-actions">
        <el-button type="primary" @click="handleTailPieceOptimizeAdd" icon="Plus">添加订单需求</el-button>
        <el-button v-if="tailPieceAddList.length > 0" type="primary" @click="handleTailPieceOptimizedSubmit()" icon="Plus">提交</el-button>
        <el-button v-if="tailPieceAddList.length > 0" type="primary" @click="handleTailPieceOptimizeDeleteAll()" icon="Delete">删除所有</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加订单需求" v-model="openTailPieceAdd" width="60%" append-to-body>
      <el-form ref="tailPieceAddRef" :model="tailPieceAddQueryParams" :rules="tailPieceAddRules" label-width="80px">
        <el-form-item label="数量" prop="piecesNumber" >
          <el-input v-model="tailPieceAddQueryParams.piecesNumber" placeholder="请输入数量" type="number" />
        </el-form-item>
        <el-form-item label="长度" prop="length" >
          <el-input v-model="tailPieceAddQueryParams.length" placeholder="请输入长度" type="number" />
        </el-form-item>
        <el-form-item label="宽度" prop="width" >
          <el-input v-model="tailPieceAddQueryParams.width" placeholder="请输入宽度" type="number" />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleTailPieceOptimizeAddSubmit">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script setup name="Package">
import {
  listPackage, preListPackage, getPackage, addPackage, updatePackage,transformPackage,listShortPackage,
  queuePackage, checkRunning, delPackage, confirmOptimize, queryOrderIds, queryPlates, querySameOrderPackage, exportOpt, addTailPlate, exportPdf, exportpdfDetail, exportoptDetail,exportPdfShow
} from "@/api/optimize/package";

import {queryMaterials} from "@/api/optimize/surplusMaterial"
import { listUtilization } from "@/api/optimize/utilization";
import useOrderStore from '@/store/modules/order'
import PDF from 'pdf-vue3'
import FakeProgress from 'fake-progress'
import { onMounted, onUnmounted } from 'vue';
import { fa } from "element-plus/es/locales.mjs";

const { proxy } = getCurrentInstance();
const router = useRouter();
const prePackageList = ref([]);
const preLoading = ref(true);
const packageList = ref([]);
const queueList = ref([]);
const open = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const preTotal = ref(0);
const queueTotal = ref(0);
const title = ref("");
const runningID = ref(0);
const pollingStopTime = ref(0);
const utilizationData = ref([{ 'name': '', 'data': [] }]);
const labelData = ref([]);
const orderStore = useOrderStore();
const openPdf = ref(false);
const totalPages = ref(0); // 这个会被pageTooltip更新
const currentPage = ref(1);
const pdfSrc = ref('');
const pdfViewer = ref(null);
const tooltipRef = ref(null);
const scale = ref(70);
const openTailPiece = ref(false);
const openSurplusMaterial = ref(false);
const tailPieceList = ref([]);
const tailPieceAddList = ref([]);
const openTailPieceAdd = ref(false);
const queueQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
});

const colors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 },
]

const currentOptimizeData = ref({
  orderNum: null,
  originalNumber: null,
  glassNum: null,
  glassArea: null,
  originalArea: null,
  totalArea: null,
  rateEdge: null,
  rateNoEdge: null,
  costTime: null,
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    glassTypeNum: null,
    name: null,
    sources: null,
    grind: null,
    isOffline: null,
    max1Cut: null,
    maxShelf: null,
    min13Cut: null,
    min1Cut: null,
    min2Cut: null,
    minWaste: null,
    plateTypeNum: null,
    trimBottom: null,
    trimLeft: null,
    trimRight: null,
    trimTop: null,
    thickNess: null,
    orderNum: null,
    status: 4
  },
  rules: {
  }
});

const tailPieceAddData = reactive({
  form:{},
  queryParams: {
    length: null,
    width: null,
    piecesNumber: null,
    id: null,
  },
  rules: {
    width: [{ required: true, message: '宽度不能为空', trigger: 'blur' }],
    length: [{ required: true, message: '长度不能为空', trigger: 'blur' }],
    piecesNumber: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  }
})
const preData = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    glassTypeNum: null,
    name: null,
    sources: null,
    grind: null,
    isOffline: null,
    max1Cut: null,
    maxShelf: null,
    min13Cut: null,
    min1Cut: null,
    min2Cut: null,
    minWaste: null,
    plateTypeNum: null,
    trimBottom: null,
    trimLeft: null,
    trimRight: null,
    trimTop: null,
    thickNess: null,
    orderNum: null,
    status: 3
  },
  rules: {
  }
});

const fake = new FakeProgress({
  timeConstant: 15000,
  autoStart: false
});

const progress = ref(0);
const percentage = computed(() => progress.value * 100)

const { queryParams, form, rules } = toRefs(data);
const { queryParams: preQueryParams, form: preForm, rules: preRules } = toRefs(preData);
const { queryParams: tailPieceAddQueryParams, form: tailPieceAddForm, rules: tailPieceAddRules } = toRefs(tailPieceAddData);

const timer = ref(null); // 用于存储定时器ID
const POLLING_INTERVAL = 4000; // 轮询间隔时间，单位毫秒

const tailPieceWidth = ref(0);
const tailPieceHeight = ref(0);
const tailPieceId = ref(0);

// 添加轮询函数
const startPolling = () => {
  // 先清除可能存在的定时器
  stopPolling();
  
  fake.start();
  
  // 创建新的定时器
  timer.value = setInterval(() => {



    // 获取队列列表
    checkRunning().then(response => {
      
      if (response.data != runningID.value) {
        progress.value = 0;
        pollingStopTime.value = 0;
        runningID.value = response.data;
        getQueueList();
        getList();
        getPreList();
        fake.end();
        fake.start();
      }
      if (response.data == 0) {
        pollingStopTime.value = pollingStopTime.value + 1;
        fake.end();
        if (pollingStopTime.value > 5) {
          //stopPolling();
        }
      } else {
        getProgress();
        getUtilization();
      }
    });
  }, POLLING_INTERVAL);
};

// 停止轮询
const stopPolling = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

function getProgress() {
  if(queueList.value.length > 0){
    progress.value = fake.progress;
  }else{
    progress.value = 1;
  }
}

function getUtilization() {
  const row = queueList.value.find(item => item.id == runningID.value);
  let instanceName = null;
  if (row) {
    instanceName = row.name;
  }
  if (instanceName) {
    const utilizationQuery = {
      instanceName: instanceName
    }
    listUtilization(utilizationQuery).then(response => {
      const data = [];
      for (let i = 0; i < response.rows.length; i++) {
        data.push((response.rows[i].currentUtilization * 100).toFixed(2));
      }
      currentOptimizeData.value.rateNoEdge = (response.rows[response.rows.length - 1].currentUtilization * 100).toFixed(2) + '%';
      currentOptimizeData.value.rateEdge = (response.rows[response.rows.length - 1].currentUtilization * 100).toFixed(2) + '%';
      utilizationData.value = [{ 'name': '', 'data': data }];
      labelData.value = [];
      for (let i = 0; i < response.rows.length; i++) {
        const timeLabel = i * 2 + 's';
        labelData.value.push(timeLabel);
      }
    });
  }
}

function updateTotalPages(num){
  totalPages.value = num;
}

/** 查询正式优化列表列表 */
function getList() {
  loading.value = true;
  queryParams.value.orderByColumn = 'createdTime';
  queryParams.value.isAsc = 'DESC';
  listShortPackage(queryParams.value).then(response => {
    packageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询预优化列表列表 */
function getPreList() {
  //preLoading.value = true;
  preQueryParams.value.orderByColumn = 'createdTime';
  preQueryParams.value.isAsc = 'DESC';
  preListPackage(preQueryParams.value).then(response => {
    prePackageList.value = response.rows;
    preTotal.value = response.total;
    preLoading.value = false;
  });
}



function getCurrentOptimizeData() {
  const row = queueList.value.find(item => item.id == runningID.value);
  if (row) {
    currentOptimizeData.value.orderNum = row.orderNum;
    currentOptimizeData.value.originalNumber = row.originalNumber;
    currentOptimizeData.value.glassNum = row.glassNum;
    currentOptimizeData.value.glassArea = row.glassArea;
    currentOptimizeData.value.originalArea = row.originalArea;
    currentOptimizeData.value.totalArea = row.totalArea;
  }
}

function getQueueList() {
  queuePackage(queueQueryParams.value).then(response => {
    queueList.value = response.rows;
    queueTotal.value = response.total;
    loading.value = false;
    getProgress();
    getCurrentOptimizeData();
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createdTime: null,
    createrId: null,
    glassTypeNum: null,
    name: null,
    sources: null,
    grind: null,
    isOffline: null,
    max1Cut: null,
    maxShelf: null,
    min13Cut: null,
    min1Cut: null,
    min2Cut: null,
    minWaste: null,
    plateTypeNum: null,
    trimBottom: null,
    trimLeft: null,
    trimRight: null,
    trimTop: null,
    thickNess: null,
    orderNum: null,
    status: null
  };
  proxy.resetForm("packageRef");
}

function onPdfLoaded(pdf){
  console.log("onpdfloaded")
}

function onPageChange(page){
  console.log(page)
}

function prevPage(){
  console.log("prevPage")
  pdfApp.setPage(currentPage.value - 1);
}
function nextPage(){
  console.log("nextPage")
  pdfApp.setPage(currentPage.value + 1);
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleDelete(row) {
  delPackage(row.id).then(response => {
    proxy.$modal.msgSuccess("删除成功");
    getQueueList();
    getList();
    getPreList();
  });
}



/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getPackage(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改优化包进程管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["packageRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePackage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          getPreList();
        });
      } else {
        addPackage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          getPreList();
        });
      }
    }
  });
}

// 队列行样式
function queueRowClassName({ row }) {
  let className = '';
  switch (row.status) {
    case 1:
      className = 'warning5';
      break;
    case 2:
      className = 'success5';
      break;
    case 3:
      className = 'danger5';
      break;
  }
  return className;
}

// 查看排版
function handleView(row) {
  openPdf.value = false; // 先关闭对话框
  title.value = "排版预览 - " + row.name;
  // 使用nextTick确保DOM更新后再打开对话框
  nextTick(() => {
     let type = row.cutReverse == 0 ? 'forward' : 'reverse';
     let version = orderStore.pdfLayoutRule || '1'
    exportPdfShow(row.id,type,'left',version).then(response => {
      pdfSrc.value = response.data
      openPdf.value = true
  });

  });
}

// 查看原因
function handleViewReason(row) {
  const reason = row.instanceMsg;
  proxy.$modal.msgError(reason);
}

function pdfLoaded(){
  console.log("pdfLoaded",pdfViewer.value)
}

function handleExportPackage(row) {
  proxy.$download.zip("/optimize/package/export/detail/" + row.id, row.name + "_package.zip");
}

function handleExportPdf(row) {
  let type = row.cutReverse == 1 ? 'reverse' : 'forward';
  exportPdf(row.id).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, row.name + "_" + type + ".pdf");
  });


}

function handlePageChange(page){
  currentPage.value = page;
}

function handleExportAll(row){
  let type_forward = 'forward'
  let type_reverse = 'reverse'
  let direction_left = 'left'
  let direction_right = 'right'
  let version_2 = orderStore.pdfLayoutRule || '1'
  console.log("version_2",version_2)

  exportpdfDetail(row.id,type_forward,direction_left,version_2).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, row.name + "_" + type_forward + "_" + direction_left + "_" + version_2 + ".pdf");
  });


  exportpdfDetail(row.id,type_forward,direction_right,version_2).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, row.name + "_" + type_forward + "_" + direction_right + "_" + version_2 + ".pdf");
  });

  exportoptDetail(row.id,type_forward).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, row.name + "_" + type_forward + ".opt");
  });

  if(row.cutReverse == 0){
    return;
  }

  type_reverse = 'reverse'
  direction_left = 'left'
  direction_right = 'right'
  exportpdfDetail(row.id,type_reverse,direction_left,version_2).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, row.name + "_" + type_reverse + "_" + direction_left + "_" + version_2 + ".pdf");
  });

  exportpdfDetail(row.id,type_reverse,direction_right,version_2).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, row.name + "_" + type_reverse + "_" + direction_right + "_" + version_2 + ".pdf");
  });

  exportoptDetail(row.id,type_reverse).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, row.name + "_" + type_reverse  + ".opt");
  });

}

function handleExportOpt(row) {
  let type = row.cutReverse == 1 ? 'reverse' : 'forward';
  const filename = row.name + "_" + type + ".opt";
  exportOpt(row.id).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, filename);
  });
}

//通用的导出pdf文件

function confirmDelete(row) {
  proxy.$modal.confirm('是否确认删除"' + row.name + '"的优化包？').then(function () {
    return delPackage(row.id);
  }).then(() => {
    getList();
    getPreList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

// 在组件激活时启动轮询
onActivated(() => {
  getList();
  getPreList();
  getQueueList();
  startPolling();
});

onUnmounted(() => {
  stopPolling();
});

// 在组件失活时停止轮询
onDeactivated(() => {
  stopPolling();
});

function handleReoptimize(row,type) {
  orderStore.setPackageId(row.id);
  if(type == 1){
        router.push("/preoptimization/optimization");
      }else {
        router.push("/order/shelf");
      }
  // orderStore.setMaxShelves(row.maxShelf);
  // queryOrderIds(row.id).then(response => {
  //   orderStore.setOrdersIds(response.data);
  //   const thicknessList = [row.thickness];
  //   orderStore.setOrdersThicknessList(thicknessList);
  //   queryPlates(row.id).then(response => {
  //     const selectOriginalIds = [];
  //     const priorityOriginalIds = [];
  //     for (let i = 0; i < response.rows.length; i++) {
  //       if (response.rows[i].isPriority == 1) {
  //         priorityOriginalIds.push(response.rows[i].originalId);
  //       } else {
  //         selectOriginalIds.push(response.rows[i].originalId);
  //       }
  //     }
  //     orderStore.setOriginalIds(selectOriginalIds);
  //     orderStore.setPriorityOriginalIds(priorityOriginalIds);
  //     if(type == 1){
  //       router.push("/preoptimization/optimization");
  //     }else {
  //       router.push("/order/shelf");
  //     }
      
  //   });

  // });

}

function closePreviewClick() {
  console.log("closePreviewClick");
  openPdf.value = false;
}

function handleTailPieceOptimize(row) {

  queryMaterials(row.optimizeResult.id).then(response =>{
    if(response.rows.length > 0){
      openTailPiece.value = true;
      const originalNumber = response.rows.length;
      tailPieceWidth.value = response.rows[originalNumber - 1].width; // 余料宽度
      tailPieceHeight.value = response.rows[originalNumber - 1].height; // 余料高度
      tailPieceId.value = row.id;
    }else {
      proxy.$modal.msgError("该优化没有产生余料")
    }
  })


}

function handleTailPieceOptimizeAdd() {
  openTailPieceAdd.value = true;
}

function handleTailPieceOptimizedSubmit() {
  addTailPlate(tailPieceId.value, tailPieceAddList.value).then(response => {
    proxy.$modal.msgSuccess("添加尾片成功");
    openTailPiece.value = false;
    getQueueList();
    getList();
    getPreList();
    tailPieceAddList.value = [];
    tailPieceId.value = 0;
    tailPieceWidth.value = 0;
    tailPieceHeight.value = 0;
    startPolling();
  });
}

function handleTailPieceOptimizeDelete(row) {
  tailPieceAddList.value = tailPieceAddList.value.filter(item => item.id !== row.id);
}

function handleTailPieceOptimizeClose() {
  if(tailPieceAddList.value.length > 0){
    proxy.$modal.confirm('关闭对话框将清空所有添加的订单需求，是否继续？').then(function () {
      return handleTailPieceOptimizeDeleteAll();
    }).then(() => {
      openTailPiece.value = false;
    }).catch(() => { });
  }else {
    openTailPiece.value = false;
  }
}

function handleTailPieceOptimizeDeleteAll() {
  tailPieceAddList.value = [];
}

function handleTailPieceOptimizeAddSubmit() {
  if (tailPieceAddQueryParams.value.width == null || tailPieceAddQueryParams.value.width == '') {
    proxy.$modal.msgError("请输入宽度");
    return;
  }
  if (tailPieceAddQueryParams.value.length == null || tailPieceAddQueryParams.value.length == '') {
    proxy.$modal.msgError("请输入长度");
    return;
  }
  if (tailPieceAddQueryParams.value.piecesNumber == null || tailPieceAddQueryParams.value.piecesNumber == '') {
    proxy.$modal.msgError("请输入数量");
    return;
  }
  let maxId = 0
  if(tailPieceAddList.value.length > 0){
    maxId = tailPieceAddList.value.reduce((max, item) => Math.max(max, item.id), 0);
  }
  tailPieceAddQueryParams.value.id = maxId + 1;
  tailPieceAddList.value.push(tailPieceAddQueryParams.value);
  openTailPieceAdd.value = false;
  tailPieceAddQueryParams.value = {};

}
//转正式优化
function handleTransform(row) {
  transformPackage(row.id).then(response => {
    proxy.$modal.msgSuccess("转正式优化成功");
    getQueueList();
    getList();
    getPreList();
  });
}
//下发
function handleConfirm(row) {
  querySameOrderPackage(row.id).then(response => {
    if (response.rows.length > 0) {
      // 构建包含相同订单的优化包信息
      const packageInfo = response.rows.map(pkg =>
        `优化包名称: ${pkg.name}, 切裁率: ${pkg.optimizeResult?.rateOpt?.toFixed(2)}%`
      ).join('\n');

      proxy.$modal.confirm(
        `以下优化包含有相同订单，确认下发后将被删除:\n${packageInfo}\n\n是否继续下发？`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString: true
        }
      ).then(function () {
        return confirmOptimize(row.id);
      }).then(() => {
        proxy.$modal.msgSuccess("确认下发成功");
        getQueueList();
        getList();
        getPreList();
      }).catch(() => { });
    } else {
      confirmOptimize(row.id).then(response => {
        proxy.$modal.msgSuccess("确认下发成功");
        getQueueList();
        getList();
        getPreList();
      });
    }
  });
}


// 添加格式化函数
const formatWithPercent = (value) => {
  return value !== null ? `${value.toFixed(2)}%` : '——';
};

function handleTailPiece(row) {
  const result_id = row.optimizeResult.id
  queryMaterials(result_id).then(response =>{
    if(response.rows.length > 0){
      tailPieceList.value = response.rows;
      openSurplusMaterial.value = true;
    }else {
      proxy.$modal.msgError("该优化没有产生余料")
    }
  })
}

const emit = defineEmits(['loaded']);

function pagesRendered(pdfApp) {
  emit('loaded', pdfApp);
}

</script>

<style scoped>
.page-btn {
  margin-right: 10px;
}

.page-info {
  margin: 0 10px;
}

.controls {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  background-color: #f0f8ff;
}

.prev-btn {
  margin-right: 10px;
}


.right-align-col {
  margin-left: auto;
}

:deep(.el-table .success5) {
  background-color: var(--el-color-success-light-5) !important;
}

:deep(.el-table .warning5) {
  background-color: var(--el-color-warning-light-5) !important;
}

:deep(.el-table .danger5) {
  background-color: var(--el-color-danger-light-5) !important;
}
.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 28px;
}
.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 12px;
}
.tail-piece-info {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.info-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-right: 10px;
}

.info-value {
  font-size: 16px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.tail-piece-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
